<!DOCTYPE HTML>
<html lang="en">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="前端图片的预览和上传、加载及下载, Casey Lu&#39;s Blog">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>前端图片的预览和上传、加载及下载 | Casey Lu&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/medias/maozhao.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 4.2.0"><link rel="alternate" href="/atom.xml" title="Casey Lu's Blog" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Casey Lu's Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>Index</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>Tags</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>Categories</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>Archives</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>About</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="Search" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Casey Lu's Blog</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			Index
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			Tags
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			Categories
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			Archives
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			About
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('嘻嘻嘻，访问本文章需要密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误哦~');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/articleimages/18.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">前端图片的预览和上传、加载及下载</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Javascript/">
                                <span class="chip bg-color">Javascript</span>
                            </a>
                        
                            <a href="/tags/LazyLoad/">
                                <span class="chip bg-color">LazyLoad</span>
                            </a>
                        
                            <a href="/tags/Axios/">
                                <span class="chip bg-color">Axios</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                技术分享
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2020-03-20
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>Word Count:&nbsp;&nbsp;
                    5.6k
                </div>
                

                

                
            </div>

        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>对于前端开发而言，和图片打交道自然是家常便饭。曾经的项目开发之中，对图片的使用也经历过不少问题，cc最近准备延伸一下，全方位的探讨在前端的多种应用场景下的图片操作，从预览上传、加载到下载到本地，同时也会分析图片的处理方式并share一些和图片素材的自用网站。</p>
<h2 id="一、图片的预览和上传">一、图片的预览和上传</h2>
<p><strong>1. 图片的预览</strong><br>
图片的预览不只是根据后台接口返回的图片地址来显示图片，更多情况下，我们需要及时预览，就是在我们选择完图片之后就及时地显示在前台页面，而不是从api中向后台再次请求来的图片，这样的预览可以减少前后台的频繁交互，减少服务端无用的图片资源，简化我们的开发过程。<br>
方案： 使用<code>FileReader</code>实现前端的及时显示</p>
<p><strong>1）FileReader的简介：</strong></p>
<p>①<code>FileReader</code>是H5中新增的对象, 负责读取文件内容</p>
<p>实例化： <code>var reader = new FileReader(); </code></p>
<p>②<code>FileReader</code>通过一系列异步接口，在主线程中访问本地文件，方法有：</p>
<blockquote>
<p><code>readAsText()</code> ：按字符读取文本文件，返回文本字符串。默认<code>UTF-8</code><br>
<code>readAsArrayBuffer(file)</code>: 按字节读取文件的内容，结果用<code>ArrayBuffer</code>对象表示<br>
<code>readAsBinaryString(file)</code>: 按字节读取任意类型的文件，返回二进制字符串，这个方法不是为了读文件，而是为了存储文件<br>
<code>readAsDataURL(file)</code>: 读取文件内容，结果用<code>data:url</code>的字符串形式表示，这段字符串的本质就是<code>DataURL</code>。<code>DataURL</code>是一种将文件(这个文件一般就是指图像或者能够嵌入到文档的文件格式) 嵌入到文档的方案。<code>DataURL</code>是将资源转换为<code>base64</code>编码的字符串形式，并且将这些内容直接存储在<code>url</code>中 → 优化网站的加载速度和执行效率。<br>
<code>abort()</code>: 终止文件读取操作</p>
</blockquote>
<p>③<code>FileReader</code>提供了一个完整的事件模型，用来识别捕获文件时的状态，事件有：</p>
<table>
<thead>
<tr>
<th>事件</th>
<th>调用描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>onabort</td>
<td>读取操作被中断时</td>
</tr>
<tr>
<td>onerror</td>
<td>读取操作发生错误时</td>
</tr>
<tr>
<td>onload</td>
<td>读取操作成功完成时</td>
</tr>
<tr>
<td>onloadend</td>
<td>读取操作完成时（不论成功/失败）</td>
</tr>
<tr>
<td>onloadatart</td>
<td>读取操作将要开始之前</td>
</tr>
<tr>
<td>onprogress</td>
<td>读取数据过程中周期性调用</td>
</tr>
</tbody>
</table>
<p><strong>2）图片的本地预览</strong></p>
<p>①通过FileReader的<code>readAsDataURL()</code>方法，我们可以<code>FileReader</code>是H5中新增的对象, 负责读取文件内容，跳过后台，直接 将本地图片显示在页面上。<br>
<code>&lt;input type=&quot;file&quot; id=&quot;imgFile&quot; /&gt;</code>上传文件<br>
<code>&lt;img id=&quot;file_img&quot; height=&quot;200&quot;&gt;</code>预览图片</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var inputFile = document.getElementById("imgFile")
inputFile.onchange = function(){
  var file = this.files[0]
  if(file){
    var reader = new FileReader();
    reader.readAsDataURL(file); // 将图片转化为base64格式
    reader.onload = function(){ // 成功读取文件
      document.getElementById("file_img").src = this.result;
    }
  }else{
    alert('图片预览失败')
  }
}
</code></pre>
<p>②通过<code>window.URL.createObjectURL</code>(blob/file)，参数既可以是Blob对象，也可是File对象，这个方法可以根据传入的参数创建一个指向该擦书对象的URL，这个URL的生命仅存在于它被创建的这个文档中</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function previewFile(){
  var inputFile = document.getElementById("imgFile")
  var file = inputFile.files[0]
  if(file.size > 1024*1024*2){ // 限制图像的大小
    alert('图片的大小不超过2MB！')
    return false
  }
  // 创建图片的url
  var imgUrl = window.URL.createObjectURL(file)
  var preview = document.getElementById("file_img")
  preview.setAttribute("src", imgUrl)
  // document.getElementById("file_img").src = imgUrl
  // 更改图片的url之后释放url
  preview.onload = function(){
    console.log('图片加载成功')
    URL.revokeObjectURL(imgUrl)
  }
}
</code></pre>
<p><strong>注：</strong> 每次调用<code>createObjectURL()</code>方法的时候，都会创建新的URL对象，所以在我们不需要的时候，必须调用<code>URL.revokeObjectURL()</code>进行安全释放，为了保证更好的性能。</p>
<p><strong>3）图片上传至服务器</strong></p>
<p>主要有以下几种方式：</p>
<ul>
<li><strong><code>&lt;input&gt;</code>标签中的<code>file</code>类型</strong><br>
file-input具备多个属性：accept、capture、multiple、files<br>
示例：<code>&lt;input type=&quot;file&quot; multiple id=&quot;imgFile&quot; accept=&quot;image/*&quot; /&gt;</code></li>
</ul>
<pre class=" language-language-javascript"><code class="language-language-javascript">let fileInput = document.getElementById('imgFile')
fileInput.onchange = function(e){
  let fileList = this.files // 列出每个所选的文件对象
  console.log(fileList)
}
</code></pre>
<ul>
<li><strong><code>FileReader</code>对象读取文件并上传</strong><br>
上面已经介绍过<code>FileReader</code>就不再过多赘述</li>
<li><strong>利用<code>FormData</code>对象上传文件</strong><br>
<strong>FromData对象的使用：</strong><br>
1）用一些键值来模拟一系列表单控件 <code>name+value-&gt;queryString</code><br>
2）异步上传二进制文件<br>
主要使用append()方法：<code>fromData.append(name,value,filename)</code>  , 其中Blob对象的默认filename是&quot;blob&quot;,File对象的默认文件名就是文件名</li>
</ul>
<pre class=" language-language-javascript"><code class="language-language-javascript">let file = document.querySelector('#imgFile').files[0]
const formData = new formData()
formData.append('usePicture', file, 'img.jpg')
</code></pre>
<ul>
<li><strong><code>axios</code>上传文件，并异步显示</strong><br>
<code>axios</code>不仅可以做数据请求，也可以实现图片上传的功能，主要是设置header中的Content-Type</li>
</ul>
<pre class=" language-language-javascript"><code class="language-language-javascript">let config = {
  headers: {
    'Content-Type': 'nultipart/form-data'
  }
}
this.$axios
       .post('serverUrl', formData, config)
       .then(res => {
         console.log(res)
       })
       .catch(err => {
         console.log(err)
       })
</code></pre>
<p>axios 也可以使用<code>onUploadProgress</code>监听上传进度</p>
<ul>
<li>
<p><strong>基于<code>form</code>表单和<code>iframe</code>自己实现Ajax请求</strong><br>
form的target属性设置为iframe的name值，表示提交到url后返回的数据显示到iframe区域中<br>
<img src="https://img-blog.csdnimg.cn/20200319223510240.png" alt="设置form和iframe"></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function loadIframe() {
  // 获取iframe内部的内容,并解析
  var str_json = $('#iframe_1').contents().find('body').text()
  var obj = JSON.parse(str_json)
  if(obj.status){
    var img = document.createElement('img')
    img.src = "/" + obj.path;
    $('#imgs').append(img);
  }
}
</code></pre>
</li>
</ul>
<h2 id="二、图片的加载">二、图片的加载</h2>
<p>除了正常的图片预览之外，还有不得不提的两种技术，预加载和懒加载</p>
<p><strong>预加载：</strong> 提前加载图片，当用户需要查看时直接从本地缓存中渲染<br>
<strong>懒加载：</strong> 一种按需加载的技术，主要目的是作为服务器前端的优化，减少请求数或者延迟请求数</p>
<p>技术本质：两者行为是相反的，一个是提前加载，一个是迟缓甚至不加载。懒加载对服务器前端有一定的缓解压力的作用，而预加载则会增加服务器端的压力。因此呢，我们主要使用的还是懒加载，它可以提升前端的性能，要隆重介绍下了。</p>
<p><strong>(一)  About Lazy Load</strong><br>
<img src="https://img-blog.csdnimg.cn/20200320232430332.png" alt="Lazy Load的实现思路"></p>
<ol>
<li>计算每张图片相对于屏幕顶端的距离offsetTop,如果图片还未出现就不需要加载，也就是如上图所示：图片到顶端距离  &gt; 滚动条滚动的高度 + 浏览器可视高度, 只有当<code>offsetTop &lt;= document.body.scrollTop + window.innerHeight</code>，图片才会加载<br>
2）运用API <code>IntersectionObserver</code>，去动态检测元素是否出现在屏幕内，jquery_lazyLoad也支持API</li>
</ol>
<p>主要介绍懒加载的几种实现方式：</p>
<ol>
<li><strong>原生js实现LazyLoad</strong><br>
根据上面1）中的原理：html中 <code>&lt;img class=&quot;pic&quot; alt=&quot;加载中&quot; data-src=&quot;./images/1.png&quot;&gt;</code></li>
</ol>
<blockquote>
<p>在IE9及以上的浏览器，可以使用<code>window.innerHeight</code>获取；但是在低版本的IE的标准模式中,可以使用<code>document.documentElement.clientHeight</code>获取；因此关于viewHeight我们写代码时要考虑浏览器兼容的情况</p>
</blockquote>
<pre class=" language-language-javascript"><code class="language-language-javascript">const imgs = document.getElementByTagName('img') // 获取所有图片的标签
const viewHeight = window.innerHeight || document.documentElement.clientHeight // 获取可视区域的高度
const scrollTop = document.body.scrollTop || document.documentElement.scrollTop // 获取滚动条滑过的高度
let cnt = 0 // 记录当前统计到哪一张图片

function lazyLoad() {
  // 遍历每一张图片，计算该图片是否加载，是否赋值真实src
  imgs.map((imgItem)=>{
    if(imgItem < scrollTop + viewHeight){
      imgItem.src = imgItem.getAttribute('data-src') // 把真实的图片src赋值
    }
  })
}
// 写一个节流函数
function throttle(method, delay){
  let timer = null
  return function(){
    let args = arguments
    clearTimeout(timer)
    timer = setTimeout(function(){
      console.log(this)
      method.apply(this.args)
    },delay)
  }
}
lazyLoad()
window.onscroll = throttle(lazyload, 200)
</code></pre>
<ol start="2">
<li><strong>运用<code>IntersectionObserver</code>动态检测元素</strong><br>
检测是否会出现在屏幕内</li>
</ol>
<pre class=" language-language-javascript"><code class="language-language-javascript">// 获取观察器示例，changes是被观察的对象数组
var observer = new IntersectionObserver(fuction(changes){
  console.log(changes)
  changes.forEach(function(index, item){
    if(item.intersectionRatio > 0 && item.intersectionRatio < 1){
      item.target.src = item.target.dataset.src // target是被观察的目标元素，是一个DOM节点对象
    }
  })
})
function addObserver(){
  var listItems = document.querySelectorAll('.img-item')
  listItems.forEach(function(item){
    // 实例的observer方法可以指定观察哪个DOM节点
    observer.observe(item) // 开始观察，obsrver的参数是一个DOM节点对象
  })
}
addObserver()
</code></pre>
<ol start="3">
<li><strong>Vue-lazyload使用</strong></li>
</ol>
<p>mint-UI组件库中的LazyLoad组件就是完全引用的<code>‘vue-lazyload’</code><br>
使用示例：<br>
html部分: <code>&lt;li v-for=&quot;imgItem in imgList&quot;&gt;&lt;img v-lazy=&quot;imgItem&quot;&gt;&lt;/li&gt;</code></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">Vue.use(Lazyload)
new Vue({
  el: #app,
  data: {
    imgList: ['imgurl1','imgurl2','imgurl3']
  }
})
</code></pre>
<p>更多关于Vue-lazyload源码和原理的解析点击<img class="emoji" draggable="false" alt="👉" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f449.png"/>：<a href="https://blog.csdn.net/u010014658/article/details/73477232" target="_blank" rel="noopener">Pick me up！~o( =∩ω∩= )m</a></p>
<p><strong>4. jQuery-lazyload的使用</strong><br>
<code>&lt;img class=&quot;lazyload&quot; data-original=&quot;ig/example.jpg&quot; width=&quot;765&quot; height=&quot;574&quot;&gt;</code><br>
<code>&lt;img class=&quot;lazyload&quot; src=&quot;img/example.jpg&quot; data-original=&quot;ig/example.jpg&quot; width=&quot;765&quot; height=&quot;574&quot;&gt;</code><br>
<code>$('img.lazyload').lazyload();</code></p>
<p>更多详见源码：</p>
<ul>
<li><a href="https://github.com/hilongjw/vue-lazyload" target="_blank" rel="noopener">vue-lazyload源码</a></li>
<li><a href="https://github.com/timelessover/jquery_lazyload" target="_blank" rel="noopener">jquery-lazyload源码</a></li>
<li><a href="https://github.com/twobin/react-lazyload" target="_blank" rel="noopener">react-lazyload源码</a></li>
</ul>
<p><strong>(二)  About PreLoad</strong></p>
<p>虽然预先加载图片会增加服务器的压力，但必须承认的是预加载对于提升用户的体验非常有效，在访问页面时，可以自由自在体会到流畅的加载速度。尤其是对于一些主力军是图片的网站来说，使用预加载可以保证图片快速、无缝隙地发布，使用户有非凡的体验，增强网站的性能和可用性。</p>
<p>实现预加载的三种技术： <a href="https://blog.csdn.net/qq_34664202/article/details/85681560" target="_blank" rel="noopener">参考文章</a></p>
<ol>
<li>
<p><strong>使用CSS + JS 实现</strong><br>
实际上，单纯使用css就可以实现预加载，非常的简单、高效</p>
<pre class=" language-language-css"><code class="language-language-css">#preload-01 { 
background: url(./image-01.png) no-repeat -9999px -9999px; 
}
#preload-02 { 
background: url(./image-02.png) no-repeat -9999px -9999px; 
}
#preload-03 { 
background: url(./image-03.png) no-repeat -9999px -9999px; 
}
</code></pre>
<p>但是该方法下的加载时间却很长会和页面上的其他内容一起加载，增添整体页面的加载时间，仍有改进的余地</p>
<p>结合JS改进来推迟预加载的时间，直至页面加载完毕，所以添加JS代码：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var preLoader = function(){
  if(document.getElementById){
    // 获取类选择器的元素，并设置background属性
    document.getElementById("preload-01").style.background = "url(./image-01.png) no-repeat -9999px -9999px";
    document.getElementById("preload-02").style.background = "url(./image-02.png) no-repeat -9999px -9999px";
    document.getElementById("preload-03").style.background = "url(./image-03.png) no-repeat -9999px -9999px";
  }
}
function addLoadEvent(func){
  var old_onload = window.onload;
  if(typeof(window.onload) != 'function'){
    window.onload = func;
  }else{
    window.onload = function(){
      if(old_onload){
        old_onload()
      }
      // 延迟preLoader()的加载时间，直到页面加载完毕
      func()
    }
  }
}
addLoadEvent(preLoader)
</code></pre>
</li>
<li>
<p><strong>使用JS实现</strong></p>
<p>即便是使用JS对CSS加载进行优化，但涉及CSS加载，在实际过程中即便看起来高效但还是会花费很多时间。而最好的选择怕不是使用纯JS代码了，并且不用考虑浏览器的兼容性。<br>
方案一： 适合大批量图片加载情况</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var images = new Array()
function preload() {
  for(let i = 0; i < preload.arguments.length; i++){
    images[i] = new Image()
    images[i].src = preload.arguments[i]
  }
}
// 把需要加载的图片的url放在其中
preload(
  "http://www.baidu.com/gallery/image1.jpg",
  "http://www.baidu.com/gallery/image2.jpg",
  "http://www.baidu.com/gallery/image3.jpg"
)

</code></pre>
<p>方案二： 适合少量图片加载情况</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function preLoader(){
  if(documents.images) {
    var img1 = new Image()
    var img2 = new Image()
    var img3 = new Image()
    img1.src = "path/to/image1.jpg"
    img2.src = "path/to/image1.jpg"
    img3.src = "path/to/image1.jpg"
  }
}
function addLoadEvent(func){
  // ...同上面的延迟加载功能函数
}
addLoadEvent(preLoader)
</code></pre>
</li>
<li>
<p><strong>使用Ajax实现</strong></p>
<p>还有一种更秀的操作——使用Ajax实现预加载<img class="emoji" draggable="false" alt="🆒" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f192.png"/>。这种方法可以利用<code>DOM</code>，不仅可以预加载图片，还会预加载<code>CSS、Javascript</code>等相关的东西。比起直接用JS，它的闪光点在于JS和CSS的加载不会影响当前页面，更加简洁高效。</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">window.onload = function(){
  setTimeout(function(){
    // XHR去请求js和css对象
    var xhr = new XMLHttpRequest()
    xhr.open('GET', 'http://domain.tld/preload.js')
    xhr.send('')
    xhr = new XMLHttpRequest()
    xhr.open('GET', 'http://domain.tld/preload.js')
    xhr.send('')
        new Image().src = "http://domain.tld/preload.png" // 预加载图片
  }, 1000); // 1s超时，防止脚本挂起
}
</code></pre>
</li>
</ol>
<h2 id="三、图片的下载">三、图片的下载</h2>
<p>除了后台直接给url点开就可以下载的方式，前端实现图片的下载主要有三种方案：</p>
<ol>
<li>
<p><strong>通过<code>&lt;a&gt;</code>的<code>download</code>属性</strong></p>
<p>html中的a标签中自带下载属性,因此我们可以这样实现下载：</p>
<p><code>&lt;a href = &quot;javascript:void()&quot; download=&quot;pic.jpg&quot; id=&quot;download&quot;&gt;下载本图片&lt;/a&gt;</code></p>
<p>在上面1.2.1使用FileReader接口预览代码的<img class="emoji" draggable="false" alt="🌰" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f330.png"/>上添加下载功能：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var inputFile = document.getElementById("imgFile")
inputFile.onchange = function(){
  var file = this.files[0]
  if(file){
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e){
      // 预览图片,this.result/e.target.result都可以
      document.getElementById("file_img").src = e.target.result;
      // 点击下载图片
      var downloadImg = document.getElementById("download");
      downloadImg.setAttribute("href", e.target.result); //给a标签设置href
    }
  }else{
    alert('图片加载失败')
  }
}
</code></pre>
<p><img class="emoji" draggable="false" alt="❗️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2757.png"/> 注：除了考虑浏览器的兼容问题之外，还有同源策略的限制，也就是说<code>href</code>指向路径必须与当前网站同源，否则就会出现下载失效或者只能下载无法改名之类的问题</p>
<p><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/a" target="_blank" rel="noopener">MDN a标签说明文档</a> 在很多实际情况下，这种方案一并不是可行的，因为我们需要下载的图片不一定是放在后台，跨域限制使得我们无法正常下载。</p>
</li>
<li>
<p><strong>通过Javascript动态创建<code>&lt;a&gt;</code>并设置download属性</strong></p>
<p>原理和限制同上,代码如下（不支持IE）：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function download(url, name){
  const aLink = document.createElement('a')
  aLink.download = name
  aLink.href = url
  // 触发a的单击事件
  aLink.dispatchEvent(new MouseEvent('click', {}))
}  
</code></pre>
<p>以导出<code>canvas</code>图像为例：<br>
<code>&lt;canvas id = &quot;canvas&quot; &gt; &lt;/canvas&gt;</code></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">const canvas = document.getElementById('canvas')
download(canvas.toDataURL('image/png'),'name.png')
</code></pre>
<p>进化版： 只要浏览器可以正常打开这个图片，就可以下载<br>
<strong>原理:</strong> 点击下载之后，新建一个隐藏的canvas ，大小和图片本身的大小一致，然后保存这个数据流，就启动了浏览器的下载。（这时候图片是以文字流的形式下载的）</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function downloadImage(url, name){
  let image = new Image()
  // 解决跨域Canvas污染问题
  image.setAttribute("crossOrigin", anonymous)
  image.onload = function(){
    let canvas = document.getElementById('canvas')
    canvas.width = image.width
    canvas.height = image.height
    let context = canvas.getContext("2d")
    context.drawImage(image, 0, 0, image.width, image.height)
    let imgUrl = canvas.toDatatURL("image/png") // 得到图片的base64编码数据
    let a = document.createElement("a")
    let event = new MouseEvent("click") // 创建一个单击事件
    a.download = name || "photo" // 设置图片名称
    a.href = url // 将生成的URL设置为a.href属性
    a.dispatchEvent(event) // 触发单击事件 
  }
  image.src = url
}
</code></pre>
</li>
<li>
<p><strong>通过Javascript创建<code>&lt;frame&gt;</code>(不推荐<img class="emoji" draggable="false" alt="❌" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/274c.png"/>)</strong></p>
<p><code>&lt;iframe height=&quot;0&quot; width = &quot;0&quot; src=&quot;pic.jpg&quot; name=&quot;saveImage&quot; id=&quot;saveImage&quot;&gt;&lt;/iframe&gt;</code><br>
<code>&lt;a href=&quot;#&quot; onclick=&quot;saveImage.document.execCommand('saveAs')&quot;&gt;Download&lt;/a&gt;</code></p>
</li>
</ol>
<ul>
<li><code>document.execCommand('SaveAs')</code> 中 SaveAs 是个非标准值，主要用来兼容 ie 不支持 <code>&lt;a&gt;</code> 标签 download 属性的场景</li>
<li><code>window.frames[&quot;iframeName&quot;].document</code> 受到同源策略的影响，如果图片地址跨域，是无法访问的 <code>&lt;frame&gt;</code> 的属性和方法</li>
</ul>
<p>此外，还可以设置<code>response, header, content-type</code></p>
<h2 id="轮播图的实现">轮播图的实现</h2>
<p>在电商平台中，轮播图的应用较为广泛：</p>
<ol>
<li>
<p><strong>JS中轮播图的实现原理</strong>：<br>
图片轮播的原理就是图片排成一行，然后准备一个只有一张图片大小的容器，对这个容器设置超出部分隐藏，来控制定时器让这些图片整体左移或者右移，这样呈现出来的效果就是图片在轮播</p>
</li>
<li>
<p><strong>多个轮播的实现</strong>： 封装一个轮播的组件，供多处使用</p>
</li>
<li>
<p><strong>Vue中的轮播组件应用实例</strong><br>
之前在复现去哪儿项目的时候，涉及到了广告轮播图的使用，主要使用的是功能强大的swiper组件：</p>
<p>具体的实现：<br>
1）Swiper.vue</p>
<p>markdown编辑器暂时不支持直接放vue代码和html代码，所以分开放<br>
<img src="https://img-blog.csdnimg.cn/20200318113302342.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0ODczNzEw,size_16,color_FFFFFF,t_70" alt="Swiper.vue中对轮播图的定义"></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">export default{
  name: 'HomeSwiper',
  props: {
    list: Array
  },
  data(){
    return {
      swiperOption: {  // 自定义轮播图的属性
        pagination: '.swiper-pagination',
        loop: true
      }
    }
  }
}
</code></pre>
<pre class=" language-language-css"><code class="language-language-css">.wrapper >>> .swiper-pagination-bullet-activate{
  background: red !important
}
.wrapper{
  overflow: hidden
  width: 100%
  height: 0
  padding-bottom: 31.25%
  /*或者直接定义height: 31.25vm，保持宽高比例*/
  background-color: darkgrey
  .swiper-img{
    width: 100%
  }
}
</code></pre>
<p>2）Home.vue中<br>
使用自定义的Swiper组件，<code>&lt;home-swiper :list=&quot;swiperList&quot;&gt;&lt;/home-swiper&gt;</code></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">import HomeSwiper from './components/Swiper'
export default{
  name: 'Home',
  components: {
    HomeSwiper
  },
  data(){
    swiperList: [] // 轮播的内容，图片信息之类,数据示例如下：
     // swiperList: [{      
     //   id: '0001',      
     //   imgUrl: 'https://img1.qunarzz.com/sight/p0/1606/be/be7426985c756fc7e2.img.jpg_600x330_4dc81148.jpg'      
     // }, {      
     //   id: '0002',      
     //   imgUrl: 'https://img1.qunarzz.com/sight/p0/1412/ad/32a5e0cd8baa07f908eab28e03d5a89f.water.jpg_600x330_353965dc.jpg'      
     // }, {      
     //   id: '0003',      
     //   imgUrl: 'https://img1.qunarzz.com/sight/p0/1603/b5/b55923ced74910b990.water.jpg_600x330_05ff4419.jpg'      
     // }]
  }
}
</code></pre>
</li>
</ol>
<h2 id="图片的压缩">图片的压缩</h2>
<p>通常在移动端项目的开发中，图片的大小非常影响加载性能，图片过大十分耗费用户流量，延缓加载时间，会使得用户的体验大打折扣。对图片进行压缩是前端优化的重中之重，在很多地方我们需要对其进行压缩，比如在上传之前对手机里选择的高达好几M的图片进行压缩。图片压缩的常见方式：插件压缩、Canvas压缩等</p>
<ol>
<li>tinypng插件压缩<br>
可以使用tinypng插件实现压缩项目图片，毕竟一一官网上传太麻烦了。<br>
官方给出了node包，gulp-tinypng，但是需要官方注册邮件，拿到key之后每月限免500张。</li>
</ol>
<p>使用<code>gulp-tinypng-compress</code>插件的具体实现：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">    var gulp = require('gulp');
    var tinypng = require('gulp-tinypng-compress');
    
    gulp.task("tinypng", function(){
        gulp.src('img/**/*.{png,jpg,jpeg}')
            .pipe(tinypng({
                key: '-HERE IS YOUR API KEY-',
                sigFile: 'images/.tinypng-sigs',
                log: true
            })).on('error', function(err) {
                console.error(err.message);
            })
            .pipe(gulp.dest('dis/img'));
    });
</code></pre>
<ol start="2">
<li>利用Canvas压缩图片<br>
也就是使用js实现图片压缩的效果，<strong>原理：</strong></li>
</ol>
<ul>
<li>利用<code>canvas</code>的<code>drawImage</code>将目标图片画到画布上</li>
<li>利用画布调整绘制尺寸，以及导出的 <code>quality</code> ，确定压缩的程度</li>
<li>利用<code>canvas</code>的<code>toDataURL</code>或者<code>toBlob</code>可以将画布上的内容导出成 base64 格式的数据</li>
</ul>
<p>Q&amp;A:</p>
<ol>
<li><strong>ios下图片翻转</strong><br>
<img class="emoji" draggable="false" alt="👉" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f449.png"/> 使用<code>import EXIF from 'exif-js'</code>来获取手机的方向，然后对<code>canvas</code>的宽高进行处理</li>
<li><strong>压缩到特定大小</strong><br>
<img class="emoji" draggable="false" alt="👉" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f449.png"/> <code>let imgDataLength = dataUrl.length</code>;<br>
<img class="emoji" draggable="false" alt="👉" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f449.png"/> 获取到数据后，判断压缩后的图片大小是否满足需求，否则就降低尺寸以及质量，再次压缩</li>
<li><strong>quality对png无效</strong><br>
<img class="emoji" draggable="false" alt="👉" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f449.png"/> 因此导出的格式统一为jpeg, 透明背景填充为白色</li>
</ol>
<pre class=" language-language-javascript"><code class="language-language-javascript">// 填充白色背景
ctx.fillStyle = fillBgColor;
ctx.fillRect(0, 0, size.w, size.h);
</code></pre>
<p>具体代码实现:</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">/**
 * 文件读取并通过canvas压缩转成base64
 * @param files
 * @param callback
 */

//EXIF js 可以读取图片的元信息  https://github.com/exif-js/exif-js
import EXIF from 'exif-js';

// 压缩图片时 质量减少的值
const COMPRESS_QUALITY_STEP = 0.03;
const COMPRESS_QUALITY_STEP_BIG = 0.06;
// 压缩图片时，图片尺寸缩放的比例，eg：0.9, 等比例缩放为0.9
const COMPRESS_SIZE_RATE = 0.9;

let defaultOptions = {
    removeBase64Header: true,
    // 压缩后允许的最大值，默认：300kb
    maxSize: 200 * 1024,
    fillBgColor: '#ffffff'
};

/**
 *  将待上传文件列表压缩并转换base64
 *  ！！！！ 注意 ： 图片会默认被转为 jpeg ， 透明底会加白色背景
 *  files : 文件列表 ，必须是数组
 *  callback : 回调，每个文件压缩成功后都会回调,
 *  options ：配置
 *  options.removeBase64Header : 是否需要删除 'data:image/jpeg;base64,'这段前缀，默认true
 *  @return { base64Data: '',fileType: '' }， //fileType强制改为jpeg
 */
export function imageListConvert(files, callback, options = {}) {
    if (!files.length) {
        console.warn('files is null');
        return;
    }

    options = { ...defaultOptions, ...options };
    // 获取图片方向－－iOS拍照下有值
    EXIF.getData(files[0], function() {
        let orientation = EXIF.getTag(this, 'Orientation');
        for (let i = 0, len = files.length; i < len; i++) {
            let file = files[i];
            let fileType = getFileType(file.name);

            //强制改为jpeg
            fileType = 'jpeg';

            let reader = new FileReader();
            reader.onload = (function() {
                return function(e) {
                    let image = new Image();
                    image.onload = function() {
                        let data = convertImage(
                            image,
                            orientation,
                            fileType,
                            options.maxSize,
                            options.fillBgColor
                        );
                        if (options.removeBase64Header) {
                            data = removeBase64Header(data);
                        }
                        callback({
                            base64Data: data,
                            fileType: fileType
                        });
                    };
                    image.src = e.target.result;
                };
            })(file);
            reader.readAsDataURL(file);
        }
    });
}

/**
 * 将 image 对象 画入画布并导出base64数据
 */
export function convertImage(
    image,
    orientation,
    fileType = 'jpeg',
    maxSize = 200 * 1024,
    fillBgColor = '#ffffff'
) {
    let maxWidth = 1280,
        maxHeight = 1280,
        cvs = document.createElement('canvas'),
        w = image.width,
        h = image.height,
        quality = 0.9;

    /**
     * 这里用于计算画布的宽高
     */
    if (w > 0 && h > 0) {
        if (w / h >= maxWidth / maxHeight) {
            if (w > maxWidth) {
                h = (h * maxWidth) / w;
                w = maxWidth;
            }
        } else {
            if (h > maxHeight) {
                w = (w * maxHeight) / h;
                h = maxHeight;
            }
        }
    }

    let ctx = cvs.getContext('2d');
    let size = prepareCanvas(cvs, ctx, w, h, orientation);

    // 填充白色背景
    ctx.fillStyle = fillBgColor;
    ctx.fillRect(0, 0, size.w, size.h);

    //将图片绘制到Canvas上，从原点0,0绘制到w,h
    ctx.drawImage(image, 0, 0, size.w, size.h);

    let dataUrl = cvs.toDataURL(`image/${fileType}`, quality);

    //当图片大小 > maxSize 时，循环压缩,并且循环不超过5次
    let count = 0;
    while (dataUrl.length > maxSize && count < 10) {
        let imgDataLength = dataUrl.length;
        let isDoubleSize = imgDataLength / maxSize > 2;

        // 质量一次下降
        quality -= isDoubleSize
            ? COMPRESS_QUALITY_STEP_BIG
            : COMPRESS_QUALITY_STEP;
        quality = parseFloat(quality.toFixed(2));

        // 图片还太大的情况下，继续压缩 。 按比例缩放尺寸
        let scaleStrength = COMPRESS_SIZE_RATE;
        w = w * scaleStrength;
        h = h * scaleStrength;

        size = prepareCanvas(cvs, ctx, w, h, orientation);

        //将图片绘制到Canvas上，从原点0,0绘制到w,h
        ctx.drawImage(image, 0, 0, size.w, size.h);

        console.log(`imgDataLength：${imgDataLength} , maxSize --> ${maxSize}`);
        console.log(`size.w:${size.w}, size.h:${size.h}, quality：${quality}`);
        dataUrl = cvs.toDataURL(`image/jpeg`, quality);
        count++;
    }

    console.log(`imgDataLength：${dataUrl.length} , maxSize --> ${maxSize}`);
    console.log(`size.w:${size.w}, size.h:${size.h}, quality：${quality}`);

    cvs = ctx = null;
    return dataUrl;
}

/**
 * 准备画布
 * cvs 画布
 * ctx 上下文
 * w : 想要画的宽度
 * h : 想要画的高度
 * orientation : 屏幕方向
 */
function prepareCanvas(cvs, ctx, w, h, orientation) {
    cvs.width = w;
    cvs.height = h;
    //判断图片方向，重置canvas大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
    let degree = 0;
    switch (orientation) {
        case 3:
            //iphone横屏拍摄，此时home键在左侧
            degree = 180;
            w = -w;
            h = -h;
            break;

        case 6:
            //iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
            cvs.width = h;
            cvs.height = w;
            degree = 90;
            // w = w;
            h = -h;
            break;
        case 8:
            //iphone竖屏拍摄，此时home键在上方
            cvs.width = h;
            cvs.height = w;
            degree = 270;
            w = -w;
            // h = h;
            break;
    }

    // console.log(`orientation --> ${orientation} , degree --> ${degree}`);
    // console.log(`w --> ${w} , h --> ${h}`);
    //使用canvas旋转校正
    ctx.rotate((degree * Math.PI) / 180);
    return { w, h };
}

/**
 * 截取 ‘data:image/jpeg;base64,’，
 * 截取到第一个逗号
 */
export function removeBase64Header(content) {
    if (content.substr(0, 10) === 'data:image') {
        let splitIndex = content.indexOf(',');
        return content.substring(splitIndex + 1);
    }
    return content;
}

export function getFileType(fileName = '') {
    return fileName.substring(fileName.lastIndexOf('.') + 1);
}

export function checkAccept(
    file,
    accept = 'image/jpeg,image/jpg,image/png,image/gif'
) {
    return accept.toLowerCase().indexOf(file.type.toLowerCase()) !== -1;
}
</code></pre>
<h2 id="网站收藏">网站收藏</h2>
<p>推荐几个比较常用的网站，值得收藏<img class="emoji" draggable="false" alt="⭐️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2b50.png"/>：</p>
<ol>
<li><a href="https://www.iconfont.cn/" target="_blank" rel="noopener">阿里巴巴矢量图标库Iconfont</a></li>
<li><a href="https://tool.css-js.com/base64.html" target="_blank" rel="noopener">图片转Base64在线网站</a></li>
<li><a href="https://jinaconvert.com/cn/" target="_blank" rel="noopener">图片的格式转换</a></li>
<li><a href="https://tinypng.com/" target="_blank" rel="noopener">Tiny_png图片压缩不失真</a></li>
<li><a href="https://www.chuangkit.com/" target="_blank" rel="noopener">创可贴平面设计素材网</a></li>
</ol>
<h2 id="好用的切图工具">好用的切图工具</h2>
<ul>
<li>Photoshop CC</li>
<li>XD</li>
<li>PxCook</li>
<li>FastStone Capture截图工具</li>
</ul>
<p>如果你看到这里了，那么你将会收获一件小干货<br>
<img class="emoji" draggable="false" alt="💥" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4a5.png"/>——HOT面试题分享：<strong>如何选择图片的格式</strong><img class="emoji" draggable="false" alt="❓" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2753.png"/>（例如png，webp(B_Cornelius)）<br>
<img src="https://img-blog.csdnimg.cn/20200321222835587.PNG?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0ODczNzEw,size_16,color_FFFFFF,t_70#pic_center" alt="图片格式的特点汇总表"></p>
<p>关于图片的总结大概就是这些了，忽然发现这篇文章像极了cc最心爱<img class="emoji" draggable="false" alt="❤️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2764.png"/>的螺蛳粉（又臭又长）<img class="emoji" draggable="false" alt="😝" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f61d.png"/> hhhhhhhhhh但整理总结的过程十分迷人的<br>
<img src="https://img-blog.csdnimg.cn/20200321151747907.png" alt=""></p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        Author:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io" rel="external nofollow noreferrer">Casey Lu</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        Link:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io/2020/03/20/18-qian-duan-tu-pian-de-yu-lan-shang-chuan-jia-zai-ji-xia-zai/">https://caseylu.gitee.io/2020/03/20/18-qian-duan-tu-pian-de-yu-lan-shang-chuan-jia-zai-ji-xia-zai/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        Reprint policy:
                    </i>
                </span>
                <span class="reprint-info">
                    All articles in this blog are used except for special statements
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    reprint polocy. If reproduced, please indicate source
                    <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>Copied successfully, please follow the reprint policy of this article</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">more</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Javascript/">
                                    <span class="chip bg-color">Javascript</span>
                                </a>
                            
                                <a href="/tags/LazyLoad/">
                                    <span class="chip bg-color">LazyLoad</span>
                                </a>
                            
                                <a href="/tags/Axios/">
                                    <span class="chip bg-color">Axios</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">谢谢大佬的小鱼干，喵~</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b739596984975414aa79',
        clientSecret: 'c5792bc3376f951910111f232176fbadfa919286',
        repo: 'L0ittle.github.io',
        owner: 'L0ittle',
        admin: "L0ittle",
        id: '2020-03-20T15-19-00',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/2020/03/28/19-javascript-bi-shi-shua-ti-xiao-jie-si/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/25.jpg" class="responsive-img" alt="Javascript笔试刷题小结（四）">
                        
                        <span class="card-title">Javascript笔试刷题小结（四）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            最近在准备美团的笔试，本来就想着继续刷心爱的leetcode，但是看了下是在赛码网OJ，，发现并不是直接写函数体那样，输入输出要有所改变，#%￥……@%#&amp;@#*&amp;^%$
输入(按行)： read_line()
输出：pri
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-28
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%AC%94%E8%AF%95%E9%9D%A2%E8%AF%95/" class="post-category">
                                    笔试面试
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Javascript/">
                        <span class="chip bg-color">Javascript</span>
                    </a>
                    
                    <a href="/tags/Leetcode/">
                        <span class="chip bg-color">Leetcode</span>
                    </a>
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/03/19/17-javascript-bi-shi-shua-ti-xiao-jie-san/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/20.jpg" class="responsive-img" alt="Javascript笔试刷题小结（三）">
                        
                        <span class="card-title">Javascript笔试刷题小结（三）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            生命不息，刷题不止，hhhhhhhhhh …  可爱的我又来了
1. Leetcode 1013. 将数组分成和相等的三个部分
**思路一：**最开始看到题目的时候cc是这么想的，既然能分成三个部分，不妨先计算每个部分的和，然后只要能成功地
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-19
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%AC%94%E8%AF%95%E9%9D%A2%E8%AF%95/" class="post-category">
                                    笔试面试
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Javascript/">
                        <span class="chip bg-color">Javascript</span>
                    </a>
                    
                    <a href="/tags/Leetcode/">
                        <span class="chip bg-color">Leetcode</span>
                    </a>
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('100')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + 'From: Casey Lu&#39;s Blog<br />'
            + 'Author: Casey Lu<br />'
            + 'Link: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="4892766072"
                   fixed='true'
                   autoplay='false'
                   theme:='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2020</span>
            <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">63.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/L0ittle" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:caseylu119@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1351238945" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1351238945" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
